package com.example.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.*;
import com.example.entity.condition.AlarmInformationCondition;
import com.example.entity.request.SearchWholeDayDataRequest;
import com.example.entity.response.AirZoneData;
import com.example.entity.response.CapacitySelectAllResponse;
import com.example.entity.response.SearchWholeDayResponse;
import com.example.entity.shape.CachedRegion;
import com.example.entity.shape.CirclePoint;
import com.example.entity.shape.PolygonPoint;
import com.example.entity.shape.WayPoint;
import com.example.mapper.BaseAirLaneMapper;
import com.example.mapper.BaseTakeoffLandMapper;
import com.example.mapper.BaseWorkMapper;
import com.example.mapper.CapacityInformationAirspaceMapper;
import com.example.utils.AlarmAnalysisUtil;
import com.example.utils.Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
public class CapacityInformationService {

    @Autowired
    private CapacityInformationAirspaceMapper capacityInformationAirspaceMapper;

    @Autowired
    private BaseTakeoffLandMapper basicTakeOffMapper;

    @Autowired
    private BaseWorkMapper baseWorkMapper;

    @Autowired
    private BaseAirLaneMapper baseAirLaneMapper;

    // 查找所有空域容量信息
    public List<CapacityInformationAirspace> findAll() {
        return capacityInformationAirspaceMapper.selectList(null);
    }

    // 根据 ID 查找空域容量信息
    public Optional<CapacityInformationAirspace> findById(Integer id) {
        return Optional.ofNullable(capacityInformationAirspaceMapper.selectById(id));
    }

    // 保存新空域容量信息
    public CapacityInformationAirspace save(CapacityInformationAirspace capacity) {
        capacityInformationAirspaceMapper.insert(capacity);
        return capacity;
    }

    // 更新空域容量信息
    public Optional<CapacityInformationAirspace> update(CapacityInformationAirspace capacity) {
        int rowsAffected = capacityInformationAirspaceMapper.updateById(capacity);
        if (rowsAffected > 0) {
            return Optional.of(capacity);
        }
        return Optional.empty();
    }

    // 根据 ID 删除空域容量信息
    public boolean delete(Integer id) {
        if (capacityInformationAirspaceMapper.selectById(id) != null) {
            capacityInformationAirspaceMapper.deleteById(id);
            return true;
        }
        return false;
    }

    // 分页查询空域容量信息
    public MicroPage<Map<String, Object>> page(Integer pageNum, Integer pageSize, AlarmInformationCondition condition) {
        Page<CapacityInformationAirspace> page = new Page<>(pageNum, pageSize);
        QueryWrapper<CapacityInformationAirspace> queryWrapper = new QueryWrapper<>();

        // 根据告警等级筛选
        if (condition.getAlertLevel() != null) {
            queryWrapper.eq("alert_level", condition.getAlertLevel());
        }

        // 根据空域编号筛选
        if (condition.getAirspaceNumber() != null && !condition.getAirspaceNumber().isEmpty()) {
            queryWrapper.like("airspace_number", condition.getAirspaceNumber());
        }

        // 根据时间范围筛选
        if (condition.getStartTime() != null && condition.getEndTime() != null) {
            queryWrapper.ge("alert_time", condition.getStartTime());
            queryWrapper.le("alert_time", condition.getEndTime());
        }

        // 根据空域类型筛选
        if (condition.getAirspaceType() != null) {
            queryWrapper.eq("airspace_type", condition.getAirspaceType());
        }

        // 执行分页查询
        Page<CapacityInformationAirspace> capacityInformationPage = capacityInformationAirspaceMapper.selectPage(page, queryWrapper);

        // 构造返回结果
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (CapacityInformationAirspace item : capacityInformationPage.getRecords()) {
            Map<String, Object> resultMap = new HashMap<>();

            // 根据空域编号动态修改字段名
            if (item.getAirspaceNumber().startsWith("航路")) {
                // 航路类型：动态字段有值，普通字段为空
                resultMap.put("dynamicFlow", item.getAirspaceFlow());
                resultMap.put("dynamicCapacity", item.getAirspaceCapacity());
                resultMap.put("airspaceFlow", "—");
                resultMap.put("airspaceCapacity", "—");
            } else {
                // 非航路类型：普通字段有值，动态字段为空
                resultMap.put("dynamicFlow", "—");
                resultMap.put("dynamicCapacity", "—");
                resultMap.put("airspaceFlow", item.getAirspaceFlow());
                resultMap.put("airspaceCapacity", item.getAirspaceCapacity());
            }

            // 其他字段保持不变
            resultMap.put("id", item.getId());
            resultMap.put("airspaceNumber", item.getAirspaceNumber());
            resultMap.put("alertLevel", item.getAlertLevel());
            resultMap.put("alertTime", item.getAlertTime());
            resultMap.put("airspaceType", item.getAirspaceType());

            resultList.add(resultMap);
        }

        // 构造分页结果
        MicroPage<Map<String, Object>> microPage = new MicroPage<>();
        microPage.setPageNum(pageNum);
        microPage.setPageSize(pageSize);
        microPage.setTotal((int) capacityInformationPage.getTotal());
        microPage.setPages((int) Math.ceil((double) capacityInformationPage.getTotal() / pageSize));
        microPage.setPageData(resultList);

        return microPage;
    }


    // 分析所有符合条件的空域容量信息（饼状图）
    public AlarmAnalysis analysis(AlarmInformationCondition condition) {
        // 创建查询条件包装器
        QueryWrapper<CapacityInformationAirspace> queryWrapper = new QueryWrapper<>();

        // 根据告警等级过滤
        if (condition.getAlertLevel() != null) {
            queryWrapper.eq("alert_level", condition.getAlertLevel());
        }

        // 根据空域编号过滤
        if (condition.getAirspaceNumber() != null && !condition.getAirspaceNumber().isEmpty()) {
            queryWrapper.like("airspace_number", condition.getAirspaceNumber());
        }

        // 根据告警时间范围过滤
        if (condition.getStartTime() != null && condition.getEndTime() != null) {
            queryWrapper.ge("alert_time", condition.getStartTime());
            queryWrapper.le("alert_time", condition.getEndTime());
        }

        // 根据空域类型过滤
        if (condition.getAirspaceType() != null) {
            queryWrapper.eq("airspace_type", condition.getAirspaceType());
        }

        // 查询所有符合条件的空域容量信息
        List<CapacityInformationAirspace> allData = capacityInformationAirspaceMapper.selectList(queryWrapper);

        // 调用工具类分析所有数据
        AlarmAnalysis calculate = AlarmAnalysisUtil.cacutate(allData);

        return calculate;
    }

    // 分析所有符合条件的空域容量信息（条形图）
    public AlarmAnalysis analysisDuplicate(AlarmInformationCondition condition) {
        // 创建查询条件包装器
        QueryWrapper<CapacityInformationAirspace> queryWrapper = new QueryWrapper<>();

        // 根据告警等级过滤
        if (condition.getAlertLevel() != null) {
            queryWrapper.eq("alert_level", condition.getAlertLevel());
        }

        // 根据空域编号过滤
        if (condition.getAirspaceNumber() != null && !condition.getAirspaceNumber().isEmpty()) {
            queryWrapper.like("airspace_number", condition.getAirspaceNumber());
        }

        // 根据告警时间范围过滤
        if (condition.getStartTime() != null && condition.getEndTime() != null) {
            queryWrapper.ge("alert_time", condition.getStartTime());
            queryWrapper.le("alert_time", condition.getEndTime());
        }

        // 根据空域类型过滤
        if (condition.getAirspaceType() != null) {
            queryWrapper.eq("airspace_type", condition.getAirspaceType());
        }

        // 查询所有符合条件的空域容量信息
        List<CapacityInformationAirspace> allData = capacityInformationAirspaceMapper.selectList(queryWrapper);

        // 调用工具类分析所有数据
        AlarmAnalysis calculate = AlarmAnalysisUtil.cacutate(allData);

        return calculate;
    }

    // 模拟触发告警信息
    public void triggerMock() {
        Utils.mockThisTimeAlarmInformation(2, 5, java.time.LocalDateTime.now()).forEach(capacityInformationAirspaceMapper::insert);
    }

    // 查询整天的数据
    public SearchWholeDayResponse searchWholeData(@RequestBody SearchWholeDayDataRequest request) {
        SearchWholeDayResponse searchWholeDayResponse = new SearchWholeDayResponse();
        CapacityInformationAirspace capacityInformationAirspace = capacityInformationAirspaceMapper.selectById(request.getId());

        QueryWrapper<CapacityInformationAirspace> wrapper = new QueryWrapper<>();
        // 获取当天的Data

        LocalDateTime localDateTime = LocalDateTime.of(2024, 9, 16, 23, 59, 59);


        // 将 LocalDateTime 转换为 Date 对象
//        Date today = Date.from(localDateTime.atZone(ZoneId.of("Asia/Shanghai")).toInstant());
//        request.setDate(today);
        LocalDateTime toMidnight = getTimeToMidnight(localDateTime);

        // 随机选择 "航路6-7" 或 "起降8-8"
        String[] airspaceNumbers = {"航路6-7", "起降8-8"};
        Random random = new Random();
        String selectedAirspaceNumber = airspaceNumbers[random.nextInt(airspaceNumbers.length)];


        wrapper.like("airspace_number", selectedAirspaceNumber);
        wrapper.ge("alert_time", toMidnight);
        wrapper.le("alert_time", localDateTime);
        wrapper.orderByAsc("alert_time");


        List<CapacityInformationAirspace> capacityInformationAirspaces = capacityInformationAirspaceMapper.selectList(wrapper);
        List<AirZoneData> list = new ArrayList<>();

        for (CapacityInformationAirspace alarm : capacityInformationAirspaces) {
            AirZoneData airZoneData = new AirZoneData();
            airZoneData.setTime(alarm.getAlertTime());
            airZoneData.setFlow(alarm.getAirspaceFlow());
            list.add(airZoneData);
        }

        searchWholeDayResponse.setAirZoneDataList(list);
        searchWholeDayResponse.setCapacityInformationAirspace(capacityInformationAirspace);
        searchWholeDayResponse.setAlarm1(10);
        searchWholeDayResponse.setAlarm2(20);
        searchWholeDayResponse.setAlarm3(30);
        List<Map<String, Object>> alarmTime = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("time", "2024-09-16 10:15:00-2024-09-16 10:30:00");
        map.put("level", 1);
        alarmTime.add(map);
        map = new HashMap<>();
        map.put("time", "2024-09-16 10:30:00-2024-09-16 10:45:00");
        map.put("level", 2);
        alarmTime.add(map);
        map = new HashMap<>();
        map.put("time", "2024-09-16 10:45:00-2024-09-16 11:00:00");
        map.put("level", 4);
        alarmTime.add(map);
        searchWholeDayResponse.setAlarmTime(alarmTime);
        searchWholeDayResponse.setCurrentTime(localDateTime.minusHours(3));

        return searchWholeDayResponse;
    }

    public List<CapacitySelectAllResponse> selectAll(@RequestBody AlarmInformationCondition condition){
        QueryWrapper<CapacityInformationAirspace> queryWrapper = new QueryWrapper<>();

        // 根据告警等级筛选
        if (condition.getAlertLevel() != null) {
            queryWrapper.eq("alert_level", condition.getAlertLevel());
        }

        // 根据空域编号筛选
        if (condition.getAirspaceNumber() != null && !condition.getAirspaceNumber().isEmpty()) {
            queryWrapper.eq("airspace_number", condition.getAirspaceNumber());
        }

        // 根据时间范围筛选
        if (condition.getStartTime() != null && condition.getEndTime() != null) {
            queryWrapper.ge("alert_time", condition.getStartTime());
            queryWrapper.le("alert_time", condition.getEndTime());
        }

        // 根据空域类型过滤
        if (condition.getAirspaceType() != null) {
            queryWrapper.eq("airspace_type", condition.getAirspaceType());
        }

        // 根据空域大小筛选
        if (condition.getAirspaceSize() != null && !condition.getAirspaceSize().isEmpty()) {
            queryWrapper.eq("airspace_size", condition.getAirspaceSize());
        }

        // 用于缓存查询结果，避免重复查询
        Map<String, CachedRegion> regionCache = new HashMap<>();

        // 查询所有符合条件的空域容量信息
        List<CapacityInformationAirspace> allData = capacityInformationAirspaceMapper.selectList(queryWrapper);
        List<CapacitySelectAllResponse> res = new ArrayList<>();
        for (CapacityInformationAirspace allDatum : allData) {
            CapacitySelectAllResponse capacitySelectAllResponse = new CapacitySelectAllResponse();
            BeanUtils.copyProperties(allDatum, capacitySelectAllResponse);
            capacitySelectAllResponse.setAirspaceGrid("空域3-5,空域2-4,空域3-8,空域10-1,空域15-4");
            String airspaceNumber = allDatum.getAirspaceNumber();
            // 检查缓存中是否已经存在该区域
            if (regionCache.containsKey(airspaceNumber)) {
                // 从缓存中提取已经查询过的区域信息
                CachedRegion cachedRegion = regionCache.get(airspaceNumber);
                capacitySelectAllResponse.setCirclePoints(cachedRegion.getCirclePoints());
                capacitySelectAllResponse.setPolygonPoints(cachedRegion.getPolygonPoints());
                capacitySelectAllResponse.setWayPoints(cachedRegion.getWayPoints());
            } else {
                // 如果缓存中没有，则根据区域类型查询，并缓存结果
                CachedRegion cachedRegion = new CachedRegion();
                // 判断airspaceNumber是否包含"起降"，如果包含，则从basic_take_off表中查询信息
                if (allDatum.getAirspaceNumber() != null && allDatum.getAirspaceNumber().contains("起降")) {
                    // 创建查询条件，根据空域编号查询起降信息
                    QueryWrapper<BaseTakeoffLand> takeOffQueryWrapper = new QueryWrapper<>();
                    takeOffQueryWrapper.eq("airspace_object_name", allDatum.getAirspaceNumber());

                    // 查询basic_take_off表
                    BaseTakeoffLand takeoffLand = basicTakeOffMapper.selectOne(takeOffQueryWrapper);
                    if (takeoffLand != null) {
                        if (takeoffLand.getCircleCenterCoordinates() != null && !takeoffLand.getCircleCenterCoordinates().isEmpty()) {
                            List<CirclePoint> circlePoints = JSON.parseArray(takeoffLand.getCircleCenterCoordinates(), CirclePoint.class);
                            capacitySelectAllResponse.setCirclePoints(circlePoints);
                            cachedRegion.setCirclePoints(circlePoints); // 缓存结果
                        }
                        if (takeoffLand.getPolygonalWaypointsCoordinates() != null && !takeoffLand.getPolygonalWaypointsCoordinates().isEmpty()) {
                            List<PolygonPoint> polygonPoints = JSON.parseArray(takeoffLand.getPolygonalWaypointsCoordinates(), PolygonPoint.class);
                            capacitySelectAllResponse.setPolygonPoints(polygonPoints);
                            cachedRegion.setPolygonPoints(polygonPoints); // 缓存结果
                        }
                    }
                }

                // 查询工作区信息
                if (allDatum.getAirspaceNumber() != null && allDatum.getAirspaceNumber().contains("作业")) {
                    // 创建查询条件，根据空域编号查询工作区信息
                    QueryWrapper<BaseWork> workspaceQueryWrapper = new QueryWrapper<>();
                    workspaceQueryWrapper.eq("airspace_object_name", allDatum.getAirspaceNumber());

                    // 查询工作区表
                    BaseWork workspaceInfo = baseWorkMapper.selectOne(workspaceQueryWrapper);
                    if (workspaceInfo != null) {
                        if (workspaceInfo.getCircleCenterCoordinates() != null && !workspaceInfo.getCircleCenterCoordinates().isEmpty()) {
                            List<CirclePoint> circlePoints = JSON.parseArray(workspaceInfo.getCircleCenterCoordinates(), CirclePoint.class);
                            capacitySelectAllResponse.setCirclePoints(circlePoints);
                            cachedRegion.setCirclePoints(circlePoints); // 缓存结果
                        }
                        if (workspaceInfo.getPolygonalWaypointsCoordinates() != null && !workspaceInfo.getPolygonalWaypointsCoordinates().isEmpty()) {
                            List<PolygonPoint> polygonPoints = JSON.parseArray(workspaceInfo.getPolygonalWaypointsCoordinates(), PolygonPoint.class);
                            capacitySelectAllResponse.setPolygonPoints(polygonPoints);
                            cachedRegion.setPolygonPoints(polygonPoints); // 缓存结果
                        }
                    }
                }

                // 查询航路点信息
                if (allDatum.getAirspaceNumber() != null && allDatum.getAirspaceNumber().contains("航路")) {
                    // 创建查询条件，根据空域编号查询航路点信息
                    QueryWrapper<BaseAirLane> routeQueryWrapper = new QueryWrapper<>();
                    routeQueryWrapper.eq("airspace_object_name", allDatum.getAirspaceNumber());

                    // 查询航路点表
                    BaseAirLane routeInfo = baseAirLaneMapper.selectOne(routeQueryWrapper);
                    if (routeInfo != null) {
                        if (routeInfo.getWaypointsCoordinates() != null && !routeInfo.getWaypointsCoordinates().isEmpty()) {
                            // 将航路点坐标解析为目标类型
                            List<WayPoint> routePoints = JSON.parseArray(routeInfo.getWaypointsCoordinates(), WayPoint.class);
                            capacitySelectAllResponse.setWayPoints(routePoints);
                            cachedRegion.setWayPoints(routePoints); // 缓存结果
                        }
                    }
                }
                // 将该区域的查询结果缓存起来
                regionCache.put(airspaceNumber, cachedRegion);
            }
            res.add(capacitySelectAllResponse);
        }
        return res;
    }

    // 获取当前时间到当天凌晨00:00的日期
    private LocalDateTime getTimeToMidnight(LocalDateTime date) {
        return date.with(LocalTime.MIDNIGHT);
    }
}
